package com.fzt.system.service.security;

import com.fzt.common.exception.ServerException;
import com.fzt.framework.service.TokenService;
import com.fzt.framework.user.UserDetail;
import com.fzt.framework.utils.TokenUtils;
import com.fzt.system.domain.vo.AccountLoginVO;
import com.fzt.system.domain.vo.TokenVO;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;


/**
 * <p>
 *
 * </p>
 *
 * @author 非洲铜
 * @since 2022-12-08
 */
@AllArgsConstructor
@Service
public class LoginService {
    private final CaptchaService        captchaService;
    private final TokenService          tokenService;
    private final AuthenticationManager authenticationManager;

    /**
     * 账号登录
     *
     * @param loginVO 账号登录入参
     * @return token
     */
    public TokenVO loginByAccount(AccountLoginVO loginVO) {

        boolean validate = captchaService.validate(loginVO.getKey(), loginVO.getCaptcha());
        if (!validate) {
            // todo 保存登录日志
            throw new ServerException("验证码错误");
        }

        Authentication authenticate;
        try {
            authenticate = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginVO.getUsername(), loginVO.getPassword())
            );
        } catch (BadCredentialsException e) {
            throw new ServerException("用户名或密码错误");
        }

        UserDetail userDetail = (UserDetail) authenticate.getPrincipal();

        String accessToken = TokenUtils.generator();
        tokenService.saveUser(accessToken, userDetail);

        // todo 保存登录日志

        return new TokenVO(accessToken);
    }

    public void logout(String accessToken) {
        // 用户信息
        UserDetail user = tokenService.getUser(accessToken);
        // 删除用户信息
        tokenService.deleteUser(accessToken);
    }
}
